package com.hay.goods.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @title: GoodsHtmlService
 * @Author HuangYan
 * @Date: 2020/7/30 21:12
 * @Version 1.0
 */
@Service
public class GoodsHtmlService {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private GoodsService goodsService;

    public void pageToStatic(Long id){

        // 获取静态化页面的数据
        Map<String, Object> map = goodsService.getItemPageData(id);

        // 使用thymeleaf上下文对象，对数据进行初始化
        Context context = new Context();
        context.setVariables(map);

        PrintWriter printWriter = null;
        try {
            // 创建输出流
            File file = new File("D:\\nginx-1.14.0\\html\\item\\"+ id + ".html");
            printWriter = new PrintWriter(file);
            templateEngine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null){
                printWriter.close();
            }
        }


    }

    public void delete(Long id) {
        File file = new File("D:\\nginx-1.14.0\\html\\item\\"+ id + ".html");
        file.deleteOnExit();
    }
}
